﻿using System;
using System.Collections.Concurrent;

namespace PddHelper.Framework
{
    /// <summary>
    /// 全局缓存类
    /// </summary>
    public class GlobalCache
    {
        // 使用ConcurrentDictionary来存储缓存数据
        private static ConcurrentDictionary<string, object> cache = new ConcurrentDictionary<string, object>();

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void Set<T>(string key, T value)
        {
            var flag = cache.TryAdd(key, value);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            object cachedValue;
            if (cache.TryGetValue(key, out cachedValue))
            {
                return (T)cachedValue;
            }
            return default(T);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Get(string key)
        {
            object cachedValue;
            if (cache.TryGetValue(key, out cachedValue))
            {
                return (string)cachedValue;
            }
            return null;
        }

        /// <summary>
        /// 从缓存中移除数据
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            object removedValue;
            cache.TryRemove(key, out removedValue);
        }

        /// <summary>
        /// 检查缓存是否存在
        /// </summary>
        /// <param name="key"></param>
        public static bool Contains(string key)
        {
            return true;
        }
    }
}